#include "UdpServer.h"
#include "Log/Log.h"

using namespace std;
using namespace Poco;
using namespace Poco::Net;

RUDPServer::RUDPServer(int iPort)
{
    SocketAddress addr("0.0.0.0", iPort);
    DatagramSocket::bind(addr);
}

UdpServer::UdpServer(int iPort, ServerProcessor* stProcess) : BaseThread(false)
{
    m_pProcessor = stProcess;
    m_pudpserver = new RUDPServer(iPort);
    Start();
}

UdpServer::~UdpServer()
{
    zlog.SInfo("~UdpServer out, listen [%d]\n", m_iPort);
}

int UdpServer::SingleStep()
{
    int length = 512;
    char buffer[length];
    
    memset(buffer, 0, length);
    SocketAddress address;
    int iRecv = m_pudpserver->receiveFrom(buffer, length, address);
    if (iRecv <= 0)
    {
        return NextLoop_Exit;
    }
    if (m_pProcessor == NULL)
    {
        return NextLoop_UseEvent;
    }
    std::string strProcessor = m_pProcessor->Process(buffer, iRecv);
    if (strProcessor.empty() == false)
    {
        m_pudpserver->sendTo(strProcessor.c_str(), strProcessor.size(), address);
    }
    return 0;
}
